package com.jsyh.maidu.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jsyh.maidu.R;
import com.jsyh.maidu.activity.me.StoreActivity;
import com.jsyh.maidu.config.ConfigValue;
import com.jsyh.maidu.config.SPConfig;
import com.jsyh.maidu.model.BaseModel;
import com.jsyh.maidu.model.CartGoods;
import com.jsyh.maidu.model.CollectGModel;
import com.jsyh.maidu.model.GoodsInfoModel2;
import com.jsyh.maidu.model.Shop;
import com.jsyh.maidu.model.ShopModel;
import com.jsyh.maidu.presenter.CollectGoodsPresenter;
import com.jsyh.maidu.presenter.DetailsPresenter;
import com.jsyh.maidu.utils.SPUtils;
import com.jsyh.maidu.utils.Utils;
import com.jsyh.maidu.views.CollectGoodsView;
import com.jsyh.maidu.views.GoodDetailsView;
import com.jsyh.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.jsyh.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.liang.library.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

/**
 * Created by Su on 2015/10/20.
 */
public class GoodsCollectActivity extends BaseActivity implements CollectGoodsView,
        GoodDetailsView, View.OnClickListener {
    private CollectGoodsPresenter mPresenter;
    private View mViewTitle;
    private ImageButton mImageButtonLeft;
    private ImageButton mImageButtonRight;
    private TextView mTextViewTitle;
    private QuickAdapter<CartGoods> mQuickAdapter;
    private QuickAdapter<Shop> shopAdapter;

    private TextView goodsCollect, shopCollect;

    private ListView mListView;

    private int type;

    private static final int GOODS = 0;
    private static final int SHOP = 1;
    private String key;
    private int page = 1;

    private int removeIndex;
    /**
     * 关注表中没有商品相关属性字段，所以不能再关注表中直接加入购物车。
     */
    private String[] mOperates = new String[]{"取消关注"};

    private DetailsPresenter mCancelCollectPresenter;

    private Transformation mTransformation;

    @Override
    protected void onResume() {
        super.onResume();
        initTransformation();
        mPresenter = new CollectGoodsPresenter(this);
        if (type == GOODS) {
            mPresenter.getCollectList();
            setIndicator(1);
        } else if (type == SHOP) {
            key = (String) SPUtils.get(this, SPConfig.KEY, "");
            if (!TextUtils.isEmpty(key)) {
                mPresenter.getCollectShop(this, key, String.valueOf(page));
            }
            setIndicator(2);
        }


        mCancelCollectPresenter = new DetailsPresenter(this);
    }

    private void initTransformation() {
        mTransformation = new RoundedTransformationBuilder()
                .cornerRadiusDp(5)
                .borderColor(Color.TRANSPARENT)
                .borderWidthDp(1)
                .oval(false)
                .build();

    }

    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_collect_goods);
        mViewTitle = findViewById(R.id.collectTitle);

        mImageButtonLeft = (ImageButton) mViewTitle.findViewById(R.id.left_imbt);
        mImageButtonLeft.setImageDrawable(getResources().getDrawable(R.mipmap.ic_back));
        mImageButtonLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mImageButtonRight = (ImageButton) mViewTitle.findViewById(R.id.right_imbt);
        mImageButtonRight.setVisibility(View.INVISIBLE);
        mTextViewTitle = (TextView) mViewTitle.findViewById(R.id.title);
        if (type == GOODS) {
            mTextViewTitle.setText("我的收藏");
        } else if (type == SHOP) {
            mTextViewTitle.setText("关注的店铺");
        }


        mListView = (ListView) findViewById(R.id.collectList);
        RelativeLayout mLayoutEmpty = (RelativeLayout) findViewById(R.id.mLayoutEmpty);
        mListView.setEmptyView(mLayoutEmpty);

        goodsCollect = (TextView) findViewById(R.id.collect_goods);
        shopCollect = (TextView) findViewById(R.id.collect_shop);
        goodsCollect.setOnClickListener(this);
        shopCollect.setOnClickListener(this);

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);

        mQuickAdapter = new QuickAdapter<CartGoods>(this, R.layout.item_goods_collect) {

            @Override
            protected void convert(final BaseAdapterHelper helper, final CartGoods item) {
                helper.setText(R.id.collect_goods_name, item.getGoods_name());
                helper.setText(R.id.collect_goods_price, "￥" + item.getGoods_price());
                Picasso.with(GoodsCollectActivity.this).load(ConfigValue.IMG_IP + item.getGoods_img()).fit().transform(mTransformation).error(R.mipmap.ic_launcher).
                        into((ImageView) helper.getView(R.id.collect_goods_img));

                helper.getView(R.id.delete_cart).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog dialog = new AlertDialog.Builder(GoodsCollectActivity.this)
                                .setTitle("确定要删除吗？")
                                .setCancelable(false)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mCancelCollectPresenter.cancelCollect(item.getGoods_id());
                                        removeIndex = helper.getPosition();
                                    }
                                }).show();
                    }
                });


                helper.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toGoodsDetail(item);
                    }
                });

                helper.getView().setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder mBuilder = new AlertDialog.Builder(GoodsCollectActivity.this);

                        mBuilder.setTitle("操作").setItems(mOperates, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        mCancelCollectPresenter.cancelCollect(item.getGoods_id());
                                        break;
                                }
                            }
                        }).show();

                        return true;
                    }
                });
            }
        };

        shopAdapter = new QuickAdapter<Shop>(this, R.layout.item_collect_shop) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final Shop item) {
                helper.setText(R.id.shop_name, item.getSupplier_name());
                Picasso.with(context).load(item.getShop_logo()).into((ImageView) helper.getView(R.id.shop_img));
                helper.getView(R.id.go_to_shop).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(GoodsCollectActivity.this, StoreActivity.class);
                        intent.putExtra("suppid", item.getId());
                        startActivity(intent);
                    }
                });
                helper.getView(R.id.delete_shop_collect).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog dialog = new AlertDialog.Builder(GoodsCollectActivity.this)
                                .setTitle("确定删除")
                                .setCancelable(false)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mPresenter.deleteCollectShop(GoodsCollectActivity.this, key, item.getId());
                                        removeIndex = helper.getPosition();
                                    }
                                }).show();
                    }
                });
                helper.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        };

    }


    //跳转到详情页
    private void toGoodsDetail(CartGoods item) {
        Intent intent = new Intent(this, GoodsInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("goodsId", item.getGoods_id());
        intent.putExtras(bundle);
        startActivity(intent);
    }

    //获取关注商品结果监听
    @Override
    public void getCollectList(CollectGModel collectGoodsModel) {
        mQuickAdapter.clear();
        mQuickAdapter.addAll(collectGoodsModel.getData());
        mListView.setAdapter(mQuickAdapter);
    }

    @Override
    public void getShopList(ShopModel model) {
        shopAdapter.clear();
        shopAdapter.addAll(model.getData());
        mListView.setAdapter(shopAdapter);
    }

    @Override
    public void deleteShopResult(BaseModel model) {
        if (model.getCode().equals("1")) {
            Toast.makeText(GoodsCollectActivity.this, model.getMsg(), Toast.LENGTH_SHORT).show();
            shopAdapter.remove(removeIndex);
            shopAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(GoodsCollectActivity.this, model.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void cancelCollectGoods(BaseModel data) {
        Utils.showToast(this, data.getMsg());
        if (data.getCode().equals("1"))
            mQuickAdapter.remove(removeIndex);
        mQuickAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.collect_goods:
                if (type == GOODS) {
                    return;
                }
                type = GOODS;
                setIndicator(1);
                onResume();
                break;
            case R.id.collect_shop:
                if (type == SHOP) {
                    return;
                }
                type = SHOP;
                setIndicator(2);
                onResume();
                break;

        }
    }

    private void setIndicator(int index) {
        Drawable col1 = getResources().getDrawable(R.mipmap.icon_collect_goods_select);
        Drawable col2 = getResources().getDrawable(R.mipmap.icon_collect_goods);
        Drawable shop1 = getResources().getDrawable(R.mipmap.icon_collect_shop_select);
        Drawable shop2 = getResources().getDrawable(R.mipmap.icon_collect_shop);
        col1.setBounds(0, 0, col1.getMinimumWidth(), col1.getMinimumHeight());
        col2.setBounds(0, 0, col2.getMinimumWidth(), col2.getMinimumHeight());
        shop1.setBounds(0, 0, shop1.getMinimumWidth(), shop1.getMinimumHeight());
        shop2.setBounds(0, 0, shop2.getMinimumWidth(), shop2.getMinimumHeight());

        if (index == 1) {
            goodsCollect.setTextColor(Color.WHITE);
            goodsCollect.setBackgroundColor(Color.parseColor("#E71F19"));
            goodsCollect.setCompoundDrawables(col1, null, null, null);
            shopCollect.setTextColor(Color.parseColor("#666666"));
            shopCollect.setBackgroundColor(Color.WHITE);
            shopCollect.setCompoundDrawables(shop2, null, null, null);
        } else {
            goodsCollect.setTextColor(Color.parseColor("#666666"));
            goodsCollect.setBackgroundColor(Color.WHITE);
            goodsCollect.setCompoundDrawables(col2, null, null, null);
            shopCollect.setTextColor(Color.WHITE);
            shopCollect.setBackgroundColor(Color.parseColor("#E71F19"));
            shopCollect.setCompoundDrawables(shop1, null, null, null);
        }
    }

    @Override
    public void onLoadGoodsInfoDatas(@Nullable GoodsInfoModel2 datas) {

    }

    @Override
    public void onAddCarShopping(@Nullable BaseModel data) {

    }

    @Override
    public void onCollectGoods(BaseModel data) {

    }

    @Override
    public void albumData(String[] albums) {

    }


}
